package com.macro.mall.wms.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.param.WmsOutStorageDto;
import com.macro.mall.wms.dto.OutStorageDto;
import com.macro.mall.wms.dto.WmsOutStorageItemDTO;
import com.macro.mall.wms.service.WmsOutStorageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmsOutStorageServiceImpl implements WmsOutStorageService {

    @Autowired
    private WmsOutStorageMapper outStorageMapper;
    @Autowired
    private WmsOutStorageItemMapper outStorageItemMapper;
    @Autowired
    private PmsStockMapper stockMapper;
    @Autowired
    private PmsOutStockMapper outStockMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private UmsStoreMapper umsStoreMapper;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private UmsMemberMapper memberMapper;

    /**
     * 新增出库单
     */
    @Override
    public CommonResult create(Long storeId, Long memberId,String memberUserName,
                               OutStorageDto outStorageDto) {
        WmsOutStorage wmsOutStorage = new WmsOutStorage();
        BeanUtils.copyProperties(outStorageDto, wmsOutStorage);
        wmsOutStorage.setStoreId(storeId);
        wmsOutStorage.setMemberId(memberId);
        wmsOutStorage.setMemberUserName(memberUserName);
        wmsOutStorage.setCreatTime(new Date());
        wmsOutStorage.setStatus(0);
        if (outStorageDto.getAgentId() != null) {
            wmsOutStorage.setType(1);
        }else {
            wmsOutStorage.setType(0);
        }
        //设置出库单编号
        wmsOutStorage.setOutStorageSn(getOutStorageSn());
        List<WmsOutStorageItem> list = outStorageDto.getSeckill_arr();
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.failed("请选择出库商品");
        }
        outStorageMapper.insertSelective(wmsOutStorage);
        for (WmsOutStorageItem wmsOutStorageItem : list) {
            WmsOutStorageItem outStorageItem = new WmsOutStorageItem();
            outStorageItem.setOutStorageId(wmsOutStorage.getId());
            outStorageItem.setStoreId(storeId);
            outStorageItem.setSkuStockId(wmsOutStorageItem.getSkuStockId());
            outStorageItem.setQuantity(wmsOutStorageItem.getQuantity());
            outStorageItem.setMemberId(memberId);
            outStorageItem.setMemberUserName(memberUserName);
            outStorageItemMapper.insertSelective(outStorageItem);
        }

        return CommonResult.success("出库成功，请审核");
    }

    /**
     * 未审核修改出库单
     */
    @Override
    public CommonResult reviewed(Long id, Long storeId, Long memberId,
                                 String memberUserName, OutStorageDto outStorageDto) {
        List<WmsOutStorageItem> list = outStorageDto.getSeckill_arr();
        WmsOutStorage wmsOutStorage = outStorageMapper.selectByPrimaryKey(id);
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.failed("参数为空");
        }

        //待新增商品
        List<WmsOutStorageItem> insertList = list.stream().filter(e -> e.getId() == null).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(insertList)) {
            for (WmsOutStorageItem outStorageItem : insertList) {
                outStorageItem.setOutStorageId(wmsOutStorage.getId());
                outStorageItem.setStoreId(storeId);
                outStorageItem.setMemberId(memberId);
                outStorageItem.setMemberUserName(memberUserName);
                outStorageItemMapper.insertSelective(outStorageItem);
            }
        }

        //待修改商品
        List<WmsOutStorageItem> updateList = list.stream().filter(e -> e.getId() != null).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(updateList)) {
            for (WmsOutStorageItem outStorageItem : updateList) {
                if (memberId.equals(outStorageItem.getMemberId())) {
                    outStorageItemMapper.updateByPrimaryKey(outStorageItem);
                }
            }
        }
        //待删除商品
        List<Long> updateSkuIds = list.stream().map(WmsOutStorageItem::getId).collect(Collectors.toList());
        WmsOutStorageItemExample itemExample = new WmsOutStorageItemExample();
        itemExample.createCriteria().andOutStorageIdEqualTo(id);
        List<WmsOutStorageItem> wmsOutStorageItems = this.outStorageItemMapper.selectByExample(itemExample);
        if(!CollectionUtils.isEmpty(wmsOutStorageItems)){
            List<WmsOutStorageItem> removeSkuList =wmsOutStorageItems.stream().filter(item -> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(removeSkuList)) {
                List<Long> removeSkuIds = removeSkuList.stream().map(WmsOutStorageItem::getId).collect(Collectors.toList());
                WmsOutStorageItemExample removeExample = new WmsOutStorageItemExample();
                removeExample.createCriteria().andIdIn(removeSkuIds);
                outStorageItemMapper.deleteByExample(removeExample);
            }
        }
        //如果传过来的经纪人id不为空，修改出库单
        if (outStorageDto.getAgentId() != null) {
            // 选择了经纪人
            if (wmsOutStorage.getAgentId() == null ) {
                //从门店出库变为门店出到经纪人
                wmsOutStorage.setAgentId(outStorageDto.getAgentId());
                wmsOutStorage.setType(1);
            }else if(!outStorageDto.getAgentId().equals(wmsOutStorage.getAgentId())){
                wmsOutStorage.setAgentId(outStorageDto.getAgentId());
            }
            wmsOutStorage.setAgentId(outStorageDto.getAgentId());
        }
        wmsOutStorage.setNote(outStorageDto.getNote());
        outStorageMapper.updateByPrimaryKey(wmsOutStorage);
        return CommonResult.success("修改出库单成功");
    }


    /**
     * 修改出库单，修改库存
     */
    @Override
    public CommonResult update(Long id,Long storeId, Long memberId, String memberUserName,Integer adminType) {
        int count = 0;
        WmsOutStorage wmsOutStorage = outStorageMapper.selectByPrimaryKey(id);
        //加一层判断如果adminType不是超级管理员判断是修改
        if(!adminType.equals(0)){
            if (!memberId.equals(wmsOutStorage.getMemberId())) {
                return CommonResult.failed("请修改自己的出库单");
            }
        }
        //修改出库单审核状态
        wmsOutStorage.setStatus(1);
        //记录完成时间
        wmsOutStorage.setFinishTime(new Date());
        WmsOutStorageItemExample example = new WmsOutStorageItemExample();
        example.createCriteria().andOutStorageIdEqualTo(wmsOutStorage.getId());
        List<WmsOutStorageItem> outItemList = outStorageItemMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(outItemList)) {
            return CommonResult.failed("出库单不存在该商品");
        }
        for (WmsOutStorageItem outStorageItem : outItemList) {
            if (wmsOutStorage.getAgentId() != null) {
                PmsStockExample pmsExample = new PmsStockExample();
                pmsExample.createCriteria().andSkuStockIdEqualTo(outStorageItem.getSkuStockId()).andAgentIdIsNull();
                List<PmsStock> storeStocks = stockMapper.selectByExample(pmsExample);
                if(!CollectionUtils.isEmpty(storeStocks)){
                    PmsStock pmsStock = storeStocks.get(0);
                    int stock = pmsStock.getStock() - outStorageItem.getQuantity();//原有数量-出库数量
                    if(stock<0){
                        PmsSkuStock pmsSkuStock = this.skuStockMapper.selectByPrimaryKey(pmsStock.getSkuStockId());
                        String spData = pmsSkuStock.getSpData();
                        StringBuilder sb = new StringBuilder();
                        List<Map> maps = JSON.parseArray(spData, Map.class);
                        for (Map<String, String> map :maps) {
                            sb.append(map.get("value")).append(";");
                        }
                        PmsProduct product = this.productMapper.selectByPrimaryKey(pmsSkuStock.getProductId());
//                        throw new RuntimeException("商品"+product.getName()+"规格为"+sb.toString()+"的库存不足，请核实");
                        return CommonResult.failed("商品"+product.getName()+"规格为"+sb.toString()+"的库存不足，请核实");
                    }else{
                        pmsStock.setStock(stock);
                        count = this.stockMapper.updateByPrimaryKeySelective(pmsStock);
                    }
                }else{
                    return CommonResult.failed("商品已被删除，请核实");
//                    throw new RuntimeException("商品已被删除，请核实");
                }
                //判断pms_stock中是否存在该商品
                pmsExample.clear();
                pmsExample.createCriteria().andSkuStockIdEqualTo(outStorageItem.getSkuStockId())
                                            .andAgentIdEqualTo(wmsOutStorage.getAgentId());
                List<PmsStock> pmsStocks = stockMapper.selectByExample(pmsExample);
                if (CollectionUtils.isEmpty(pmsStocks)) {
                    //给经纪人加库存
                    PmsStock pmsStock = new PmsStock();
                    pmsStock.setMemberUserName(outStorageItem.getMemberUserName());
                    pmsStock.setMemberId(outStorageItem.getMemberId());
                    pmsStock.setStoreId(outStorageItem.getStoreId());
                    pmsStock.setStock(outStorageItem.getQuantity());
                    pmsStock.setAgentId(wmsOutStorage.getAgentId());
                    pmsStock.setSkuStockId(outStorageItem.getSkuStockId());
                    this.stockMapper.insertSelective(pmsStock);
                } else {
                    //存在，修改库存
                    PmsStock pmsStock = pmsStocks.get(0);
                    pmsStock.setStock(pmsStock.getStock()+outStorageItem.getQuantity());
                    this.stockMapper.updateByPrimaryKeySelective(pmsStock);
                }
            } else {
                //判断pms_stock中是否存在该商品
                PmsStockExample pmsExample = new PmsStockExample();
                pmsExample.createCriteria().andSkuStockIdEqualTo(outStorageItem.getSkuStockId())
                                            .andAgentIdIsNull();
                List<PmsStock> pmsStocks = stockMapper.selectByExample(pmsExample);
                if (!CollectionUtils.isEmpty(pmsStocks)) {
                    //存在，修改库存
                    PmsStock pmsStock = pmsStocks.get(0);
                    PmsSkuStock pmsSkuStock = this.skuStockMapper.selectByPrimaryKey(pmsStock.getSkuStockId());
                    int stock = pmsStock.getStock() - outStorageItem.getQuantity();//原有数量-出库数量
                    if(stock>0){
                        pmsStock.setStock(stock);
                        count = stockMapper.updateByPrimaryKey(pmsStock);
                        pmsSkuStock.setStock(pmsSkuStock.getStock()-outStorageItem.getQuantity());
                        this.skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
                    }else{
                        String spData = pmsSkuStock.getSpData();
                        StringBuilder sb = new StringBuilder();
                        List<Map> maps = JSON.parseArray(spData, Map.class);
                        for (Map<String, String> map :maps) {
                            sb.append(map.get("value")).append(";");
                        }
                        PmsProduct product = this.productMapper.selectByPrimaryKey(pmsSkuStock.getProductId());
                        throw new RuntimeException("商品"+product.getName()+"规格为"+sb.toString()+"的库存不足，请核实");
                    }
                }
            }
        }
        //修改出库表数据
        outStorageMapper.updateByPrimaryKeySelective(wmsOutStorage);
        if (count > 0) {
            return CommonResult.success("修改成功");
        } else {
            return CommonResult.failed("修改失败");
        }
    }

    /**
     * 删除未审核的出库单
     */
    @Override
    public CommonResult delete(Long id, Long memberId) {
        WmsOutStorage wmsOutStorage = outStorageMapper.selectByPrimaryKey(id);
        if (!memberId.equals(wmsOutStorage.getMemberId())) {
            return CommonResult.failed("用户只能删除自己的出库单");
        }
        if (wmsOutStorage.getStatus().equals(1)) {
            return CommonResult.failed("已完成的出库单不能删除");
        }

        WmsOutStorageItemExample example = new WmsOutStorageItemExample();
        example.createCriteria().andOutStorageIdEqualTo(wmsOutStorage.getId());
        List<WmsOutStorageItem> items = outStorageItemMapper.selectByExample(example);
        //删除的出库单下的商品
        List<Long> removeIds = items.stream().map(WmsOutStorageItem::getId).collect(Collectors.toList());
        example.createCriteria().andIdIn(removeIds);
        outStorageItemMapper.deleteByExample(example);
        int delete = outStorageMapper.deleteByPrimaryKey(id);
        if (delete == 1) {
            return CommonResult.success("删除成功");
        } else {
            return CommonResult.failed("删除失败");
        }
    }

    @Override
    public List<WmsOutStorageItemDTO> getOutStorageItems(Long orderId) {
        List<WmsOutStorageItemDTO> list = new ArrayList<>();
        WmsOutStorageItemExample example = new WmsOutStorageItemExample();
        example.createCriteria().andOutStorageIdEqualTo(orderId);
        List<WmsOutStorageItem> items = outStorageItemMapper.selectByExample(example);
        Map<Long,PmsProduct> productMap = new HashMap<>();
        for (WmsOutStorageItem item:items) {
            WmsOutStorageItemDTO dto = new WmsOutStorageItemDTO();
            BeanUtils.copyProperties(item,dto);
            PmsProduct product = null;
            PmsSkuStock pmsSkuStock = this.skuStockMapper.selectByPrimaryKey(item.getSkuStockId());
            if (pmsSkuStock == null) {
                continue;
            }
            BeanUtils.copyProperties(pmsSkuStock,dto);
            if(productMap.get(item.getSkuStockId())!=null){
                product = productMap.get(item.getSkuStockId());
            }else{
                product = this.productMapper.selectByPrimaryKey(pmsSkuStock.getProductId());
                productMap.put(product.getId(), product);
            }
            dto.setPic(product.getPic());
            dto.setName(product.getName());
            list.add(dto);
        }
        return list;
    }


    /**
     * 查询门店所有出库单
     */
    @Override
    public List<WmsOutStorageDto> getList(Long storeId, WmsOutStorage wmsOutStorage, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        WmsOutStorageExample example = new WmsOutStorageExample();
        WmsOutStorageExample.Criteria criteria = example.createCriteria();
        //根据出库单code和状态模糊查询
        if (wmsOutStorage.getOutStorageSn()!= null) {
            criteria.andOutStorageSnLike("%" + wmsOutStorage.getOutStorageSn() + "%");
        }
        if (wmsOutStorage.getStatus() != null) {
            criteria.andStatusEqualTo(wmsOutStorage.getStatus());
        }
        if (wmsOutStorage.getType() != null) {
            criteria.andTypeEqualTo(wmsOutStorage.getType());
        }
        if (storeId != null) {
            criteria.andStoreIdEqualTo(storeId);
        }
        example.setOrderByClause("creat_time desc");
        //查询该用户所有出库单
        List<WmsOutStorage> wmsOutStorages = outStorageMapper.selectByExample(example);
        List<WmsOutStorageDto> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(wmsOutStorages)) {
            wmsOutStorages.forEach(e->{
                WmsOutStorageDto dto = new WmsOutStorageDto();
                BeanUtils.copyProperties(e,dto);
                if (e.getType().equals(1) && e.getAgentId() != null) {
                    UmsMember member = memberMapper.selectByPrimaryKey(e.getAgentId());
                    dto.setPhone(member.getPhone());
                    dto.setRealName(member.getRealName());
                }
                result.add(dto);
            });
        }
        return result;
    }

    /**
     * 根据id查询出库单详情
     */
    @Override
    public CommonResult<OutStorageDto> getOutStorage(Long id) {
        WmsOutStorage storage = outStorageMapper.selectByPrimaryKey(id);
        WmsOutStorageItem storageItem = null;
        OutStorageDto outStorageDto = toDTO(storage,storageItem);
        return CommonResult.success(outStorageDto);
    }

    /**
     * 根据出库单返回出库单和商品的封装
     *
     * @param storage
     * @return
     */
    private OutStorageDto toDTO(WmsOutStorage storage, WmsOutStorageItem storageItem) {
        OutStorageDto dto = new OutStorageDto();
        dto.setId(storage.getId());
        dto.setSkuStockId(storageItem.getSkuStockId());
        dto.setOutStorageId(storageItem.getOutStorageId());
        dto.setQuantity(storageItem.getQuantity());
        dto.setStatus(storage.getStatus());
        dto.setCreatTime(storage.getCreatTime());
        dto.setOutStorageSn(storage.getOutStorageSn());
        dto.setMemberId(storage.getMemberId());
        dto.setMemberUserName(storage.getMemberUserName());
        dto.setType(storage.getType());
        dto.setStoreId(storage.getStoreId());
        dto.setFinishTime(storage.getFinishTime());
        //查询该出库单下所有出库商品
        WmsOutStorageItemExample itemExample = new WmsOutStorageItemExample();
        itemExample.createCriteria().andOutStorageIdEqualTo(storage.getId());
        List<WmsOutStorageItem> items = outStorageItemMapper.selectByExample(itemExample);
        dto.setSeckill_arr(items);
        return dto;
    }

    /**
     * 获取出库单的单号
     * @return
     */
    private String getOutStorageSn(){
        String outStorageSn = "";
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        WmsOutStorageExample example = new WmsOutStorageExample();
        example.createCriteria().andOutStorageSnLike(sdf.format(date)+"%");
        List<WmsOutStorage> wmsOutStorages = outStorageMapper.selectByExample(example);
        if(wmsOutStorages.size() == 0){
            //当天还没有新建出库单
            outStorageSn = sdf.format(date).substring(0, 8) + "0000";
        }else{
            String sn = wmsOutStorages.get(wmsOutStorages.size() - 1).getOutStorageSn();
            Integer count = Integer.parseInt(sn.substring(8));
            //当天新建了count条出库单，取count+1作为新的编号的后缀
            outStorageSn = sdf.format(date).substring(0, 8) + String.format("%04d", count+1);
        }
        return outStorageSn;
    }
}
